#include "Timer.h"
#include <fmt/format.h>
#include <fmt/color.h>
#include <fmt/ostream.h>
#include <fmt/os.h>

namespace yansu::common{

std::map<std::string, Timer::TimerRecord> Timer::records_;

void Timer::PrintAllRecords(){
    for(auto &[name , record] : records_){
        fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,"func name : {0} , time_used :\n",name); 
        for(auto &time_used : record.time_used_all_in_ms_){
            fmt::print(fg(fmt::color::green)," {0} ", time_used); 
        }
        fmt::print("\n"); 
    }
}
void Timer::DumpIntoFile(const std::string& file_name){
    auto out = fmt::output_file(file_name);
    for(auto &[name , record] : records_){
        out.print("func name : {0} , time_used :\n",name); 
        for(auto &time_used : record.time_used_all_in_ms_){
            out.print(" {0} ", time_used); 
        }
        out.print("\n"); 
    }
}
double Timer::GetMeanTime(const std::string& func_name){
    if(records_.find(func_name) == records_.end()){
        fmt::print(fg(fmt::color::dark_red) | fmt::emphasis::bold,"failed to find func_name\n"); 
        return -1.0;
    }
    else{
        const auto &record = records_.find(func_name)->second;
        double all_times = 0.0;
        auto len = record.time_used_all_in_ms_.size();
        for(auto &time_used : record.time_used_all_in_ms_){
            all_times += time_used;
        }
        return (all_times/len);
    }   
}

}